import { ElButton, ElDialog } from "element-plus"
import { createVNode, defineComponent, reactive, render } from "vue"
import './dialog.scss';

const DialogComponent = defineComponent({
    props: {
        options: {
            type: Object,
            default: () => {}
        }
    },
    setup(props, ctx) {
        const state = reactive({
            isShow: false,
            options: props.options
        })

        // 暴露一个可以让外部组件调用的方法
        ctx.expose({
            showDialog: (options) => {
                state.isShow = true;
                state.options = options;
            }
        })

        // 关闭弹出框
        const cancelDialog = () => {
            state.isShow = false;
        }
        // 确认事件
        const confirmsHanlde = () => {
            state.isShow = false;
            state.options.callback && state.options.callback(state.options.content)
        }

        return () => (
            <ElDialog
                v-model={state.isShow}
                // title={state.options.title}
                draggable
            >
                {{
                    header: () => (<div class="el_header_text">
                        {state.options.title}
                    </div>),
                    default: () => (
                        <textarea
                            class="textarea"
                            rows={state.options.rows}
                            v-model={state.options.content}
                        ></textarea>
                    ),
                    footer: () => state.options.footer && (
                        <div>
                            <ElButton onClick={cancelDialog}>取消</ElButton>
                            <ElButton onClick={confirmsHanlde} type="primary">确认</ElButton>
                        </div>
                    )
                }}
            </ElDialog>
        )
    }
})

let vnode = null;
export const $dialog = (options) => {
    if(!vnode) {
        // 创建div元素
        const el = document.createElement("div");
        // 创建虚拟节点
        vnode = createVNode(DialogComponent, { options });
        // 将虚拟节点渲染成真实节点
        render(vnode, el);
        // 将真实节点添加到body中
        document.body.appendChild(el);
    }
    // 调用组件的方法，显示组件
    const { showDialog } = vnode.component.exposed;
    showDialog(options)
}